//
//  ViewController.m
//  mpoi
//
//  Created by thomasho on 15/11/6.
//  Copyright © 2015年 thomasho. All rights reserved.
//

#import "ViewController.h"
#import "MyScrollView.h"
#import "SVProgressHUD.h"
#import "UIView+expanded.h"
#import "NSString+expanded.h"

#define colorRed @"red"
#define colorGreen @"green"
#define colorYellow @"yellow"
#define poiWidth 30
#define poiHeight 60

@interface ViewController ()<UIActionSheetDelegate,UITextFieldDelegate,UIActionSheetDelegate>{
    BOOL isRegionMap;
    NSInteger curSelectID;
}
@property (nonatomic,strong) MyScrollView *scrollView_map;
@property (nonatomic,strong) NSArray *spotArray;
@property (nonatomic,strong) NSArray *relicArray;
@property (strong, nonatomic) IBOutlet UIBarButtonItem *rightBarButton;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //准备数据
    self.spotArray = [DBData Select:tb_spot Filelds:nil condition:SF(@"region_id='%@' and isdelete = '0'", self.dataDict[@"id"])];
    if (self.spotArray.count) {
        NSMutableArray *marray = [NSMutableArray array];
        for (NSNumber *number in [self.spotArray valueForKey:@"id"]) {
            [marray addObject:SF(@"'%@'", number)];
        }
        NSString *spotids = [marray componentsJoinedByString:@","];
        self.relicArray = [DBData Select:tb_relic Filelds:nil condition:SF(@"spot_id in (%@) and isdelete = '0'", spotids)];
    }
}
- (void)viewWillAppear:(BOOL)animated {
//    curSelectID = 0;

    [super viewWillAppear:animated];
    if (!self.scrollView_map) {
        self.scrollView_map = [[MyScrollView alloc] initWithFrame:self.view.bounds];
        isRegionMap = 1;
        NSString *pic = [self.dataDict valueForJSONStrKey:@"map_img"];
        if(pic.length)[self.scrollView_map.imageView imageWithURL:pic];
        [self performSelectorInBackground:@selector(WaitForMap:) withObject:self.spotArray];
    }
    [self.view insertSubview:self.scrollView_map atIndex:0];
}


- (void)WaitForMap:(NSArray *)array {
    @autoreleasepool {
        while(!self.scrollView_map.imageView.image) {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
        //        [self showStation:array atIndex:0];
        [self performSelectorOnMainThread:@selector(showStation:) withObject:array waitUntilDone:NO];
    }
}

- (void)showStation:(NSArray *)array {
    [self showStation:array atIndex:0];
}
#pragma mark - showPoint

- (CGPoint)point:(NSDictionary*)dict {
    CGSize size = self.scrollView_map.imageView.image.size;
    NSArray *array = [[dict valueForJSONStrKey:@"map_path"] componentsSeparatedByString:@","];
    float xAxis = [array[0] floatValue];
    float yAxis = [array.lastObject floatValue];
    if (xAxis<=1||yAxis<=1) {
        xAxis = size.width*xAxis;
        yAxis = size.height*yAxis;
    }
    return CGPointMake(xAxis, yAxis);
}
- (void)removeStations
{
    //self.scrollView_map.scrollEnabled = YES;
    for (UIView *view in self.scrollView_map.imageView.subviews) {
//        if (view.tag==999) {
            [view removeFromSuperview];
//        }
    }
}
- (void)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
    //    return;
    //self.scrollView_map.zoomScale = scale;
    CGRect zoomRect;
    zoomRect.size.height = self.scrollView_map.frame.size.height / scale;
    zoomRect.size.width  = self.scrollView_map.frame.size.width  / scale;
    zoomRect.origin.x = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y = center.y - (zoomRect.size.height / 2.0);
    [self.scrollView_map zoomToRect:zoomRect animated:YES];
}

- (void)showStation:(NSArray*)array atIndex:(NSInteger)idx
{
    if (idx == 0) {
        [self removeStations];
    }
    //注意坑：0>array.count-1，由于NSUInteger到array为空时候，-1是很大的正值
    if (idx>=array.count) {
        return;
    }
    NSDictionary *dict = [array objectAtIndex:idx<0?0:idx];
    CGPoint point = CGPointMake([self point:dict].x,[self point:dict].y);
    if (array.count == 1) {
        [self zoomRectForScale:1.0 withCenter:point];
    }

    NSString *name = [dict valueForJSONStrKey:@"name"];
    CGFloat w = poiWidth/self.scrollView_map.zoomScale;
    CGFloat h = poiHeight/self.scrollView_map.zoomScale;

    UIButton *view = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, w, h)];
    [view addTarget:self action:@selector(bindButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [view setBackgroundImage:[UIImage imageNamed:[[dict valueForJSONStrKey:@"beacon_id"] integerValue]?colorGreen:colorYellow] forState:UIControlStateNormal];
    //    view.delegate = self;
    [view setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [view.titleLabel setFont:Font(40)];
    view.titleLabel.adjustsFontSizeToFitWidth = YES;
    view.titleLabel.minimumScaleFactor = 1;
    view.titleLabel.numberOfLines = 0;
    view.clipsToBounds = YES;
    [view setTitle:name forState:UIControlStateNormal];
//    view.tag = 999;
    view.alpha = 0;
    view.autoresizesSubviews = YES;

    view.tag = [[dict valueForJSONStrKey:@"id"] integerValue];
    view.center = point;
    view.alpha = 1;
    [self.scrollView_map.imageView addSubview:view];
    [self showStation:array atIndex:idx+1];
    
}


- (IBAction)floorButtonClicked:(UIButton*)sender {
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil];
    for (NSDictionary *dict in self.spotArray) {
        if([dict valueForJSONKey:@"map_img"])[sheet addButtonWithTitle:[dict valueForKey:@"name"]];
    }
    sheet.tag = 100;
    [sheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (actionSheet.tag==100&&actionSheet.cancelButtonIndex != buttonIndex) {
//        self.scrollview.tag = buttonIndex-1;
        NSDictionary *dict = [self.spotArray objectAtIndex:buttonIndex-1];
        self.title = [dict valueForKey:@"name"];
        [self.scrollView_map.imageView imageWithURL:[dict valueForKey:@"map_img"]];
        NSArray *array = [DBData Select:tb_relic Filelds:nil condition:SF(@"isdelete='0' and spot_id ='%@'", [dict valueForKey:@"id"])];
        [self performSelectorInBackground:@selector(WaitForMap:) withObject:array];
    }else if (101 == actionSheet.tag) {
        NSString *title = [actionSheet buttonTitleAtIndex:buttonIndex];
        if ([title isEqualToString:@"绑定设备"]){
            [self performSegueWithIdentifier:@"beacon" sender:self];
        }else if([title isEqualToString:@"取消"]){
            curSelectID = 0;
        }else if([title isEqualToString:@"修改位置"]){
            //            self.scrollView_map.imageView.tag = actionSheet.tag;别用会扰乱tag。
            [(UIButton*)[self.scrollView_map.imageView viewWithTag:curSelectID] setBackgroundImage:[UIImage imageNamed:colorRed] forState:UIControlStateNormal];
        }else if([title isEqualToString:@"取消绑定设备"]){
            [self uploadData:@""];
        }
    }
}

- (UIButton *)buttonWithTag:(NSInteger)tag {
    UIButton *btn = (UIButton*)[self.scrollView_map.imageView viewWithTag:tag];
    if (!btn) {
        btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 120/self.scrollView_map.zoomScale, 40/self.scrollView_map.zoomScale)];
        [btn setBackgroundImage:[UIImage imageNamed:@"red.png"] forState:UIControlStateNormal];
        btn.tag = tag;
        btn.titleLabel.lineBreakMode = NSLineBreakByCharWrapping;
        btn.titleLabel.adjustsFontSizeToFitWidth = YES;
        btn.titleLabel.font = [UIFont systemFontOfSize:40];
        btn.titleLabel.minimumScaleFactor = .1;
        [btn setBackgroundImage:[UIImage imageNamed:colorGreen] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(bindButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
        [self.scrollView_map.imageView addSubview:btn];
    }
    return btn;
}

- (void)imageButtonClicked:(NSString*)pt{
    if (curSelectID) {
        [[self.scrollView_map.imageView viewWithTag:curSelectID] setCenter:CGPointFromString(pt)];
    }else{
        UIButton *btn = [self buttonWithTag:999];
        btn.center = CGPointFromString(pt);
    }
}

- (void)scrollViewDidScroll:(MyScrollView *)scrollView {
    for (UIView *view in scrollView.imageView.subviews) {
        CGRect frame = view.frame;
        CGPoint center = view.center;
        if (view.tag) {
            frame.size.width = poiWidth/scrollView.zoomScale;
            frame.size.height = poiHeight/scrollView.zoomScale;
            view.frame = frame;
            view.center = center;
        }
    }
}
- (IBAction)bindButtonClicked:(UIButton*)sender {
    if (curSelectID) {
        [[Utility Share] alert:@"设备未保存" delegate:self buttons:@[@"放弃",@"立即保存"] tag:100];
    }else{
        curSelectID = sender.tag;
        [(UIButton*)[self.scrollView_map.imageView viewWithTag:curSelectID] setBackgroundImage:[UIImage imageNamed:colorRed] forState:UIControlStateNormal];
    }
    /*else
    if (sender.tag) {
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"修改位置",@"绑定设备",@"取消绑定设备", nil];
        curSelectID = sender.tag;
        sheet.tag = 101;
        [sheet showInView:self.view];
    }else{
        [self performSegueWithIdentifier:@"poi" sender:sender];
    }*/
}

- (IBAction)uploadButtonClicked:(UIButton*)sender {

}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
        NSDictionary *spotOrRelic = nil;
        if (isRegionMap) {
            spotOrRelic = [DBData Select:tb_spot Filelds:nil condition:SF(@"id=%ld", (long)curSelectID)].lastObject;
        }else{
            spotOrRelic = [DBData Select:tb_relic Filelds:nil condition:SF(@"id=%ld", (long)curSelectID)].lastObject;
        }
        NSString *bid = [spotOrRelic valueForJSONStrKey:@"beacon_id"];
    if (alertView.tag==100&&buttonIndex) {
        [self uploadData:bid];
    }else{
        UIView *view = [self.scrollView_map.imageView viewWithTag:curSelectID];
        [(UIButton*)view setBackgroundImage:[UIImage imageNamed:bid.integerValue?colorGreen:colorYellow] forState:UIControlStateNormal];
        curSelectID = 0;
    }
}

- (void)uploadData:(NSString *)bid {
    __block UIView *view = [self.scrollView_map.imageView viewWithTag:curSelectID];
    NSString *pt = SF2(@"%02f,%02f", view.center.x, view.center.y);
    NSDictionary *dic = @{(isRegionMap?@"spot_id":@"relic_id"):@(curSelectID),@"map_path":pt};
    [HttpRequest request:isRegionMap?url_editspot:url_editrelic data:dic block:^(id data, id error) {
        if (data) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [(UIButton*)view setBackgroundImage:[UIImage imageNamed:bid.integerValue?colorGreen:colorYellow] forState:UIControlStateNormal];
                curSelectID = 0;
            });
        }else{
            [[Utility Share] alert:error];
        }
    }];
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"beacon"]) {
        NSDictionary *spotOrRelic = nil;
        if (isRegionMap) {
            spotOrRelic = [DBData Select:tb_spot Filelds:nil condition:SF(@"id=%ld", (long)curSelectID)].lastObject;
        }else{
            spotOrRelic = [DBData Select:tb_relic Filelds:nil condition:SF(@"id=%ld", (long)curSelectID)].lastObject;
        }
        NSDictionary *dict = [DBData Select:tb_beacon Filelds:nil condition:SF(@"id=%@",spotOrRelic[@"beacon_id"])].lastObject;
        [segue.destinationViewController setValue:dict forKey:@"dataDict"];
        [segue.destinationViewController setValue:self forKey:@"sender"];
    }else if([segue.identifier isEqualToString:@"search"]){
        [segue.destinationViewController setValue:isRegionMap?self.spotArray:self.relicArray forKey:@"dataArray"];
        [segue.destinationViewController setValue:self forKey:@"sender"];
    }
}

- (void)updateBeacon:(NSDictionary *)beacon {

}

#pragma mark - **************** 搜索景点、文物
- (IBAction)searchButtonClicked:(id)sender {
    if (curSelectID) {
        [[Utility Share] alert:@"设备未保存" delegate:self buttons:@[@"暂不",@"立即保存"] tag:100];
    }else{
        [self performSegueWithIdentifier:@"search" sender:self];
    }
}
- (void)searchBack:(NSDictionary *)dict {
    BOOL flag = YES;
    for (UIView *view in self.scrollView_map.imageView.subviews) {
        if (view.tag == [[dict valueForJSONStrKey:@"id"] integerValue]) {
            [self zoomRectForScale:self.scrollView_map.zoomScale withCenter:view.center];
            curSelectID = view.tag;
            [(UIButton*)view setBackgroundImage:[UIImage imageNamed:colorRed] forState:UIControlStateNormal];
            flag = NO;
            break;
        }
    }
    if (flag) {
        NSDictionary *spot = [DBData Select:tb_spot Filelds:nil condition:SF(@"id=%@", dict[@"spot_id"])].lastObject;
        if (spot) {
            [Utility alertError:SF(@"当前地图上未找到,请切换到'%@'.",spot[@"name"])];
        }else

        [Utility alertError:@"当前地图上未找到,请切换到大地图"];
    }
}
@end
